package com.yaoweigroup.community.ui.home;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.a.an;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.Annouce;
import com.yaoweigroup.community.ui.home.DiscountDetailActivity.MyImageGetter;
import com.yaoweigroup.community.ui.home.DiscountDetailActivity.MyImageGetter.URLDrawable;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.MD5;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * 公告详情
 * 
 * @author xi
 * 
 */
public class AnnounceDetailActivity extends Activity implements OnClickListener {

	private RelativeLayout left_rl;
	private TextView title_tv;
	private TextView time_tv;
	private TextView content_tv;
	private Dialog dialog;
	private ObjectMapper mapper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_announce_detail);

		mapper = new ObjectMapper();
		dialog = DialogUtil.createWaitDialog(this, "正在获取中...");

		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);

		title_tv = (TextView) findViewById(R.id.title_tv);
		time_tv = (TextView) findViewById(R.id.time_tv);
		content_tv = (TextView) findViewById(R.id.content_tv);
		ann = (Annouce) getIntent().getSerializableExtra("detail");
		if (ann != null) {
			title_tv.setText(ann.getNewtitle());
			time_tv.setText(ann.getAddtime() + "      " + ann.getAuthor());
			content_tv.setText(Html.fromHtml(ann.getNewcontent(),
					new MyImageGetter(this, content_tv), null));
		} else {
			String id = getIntent().getStringExtra("id");
			obtainDetail(id);
		}
	}

	private Annouce ann;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		}
	}

	private void obtainDetail(String id) {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("id", id);
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getNotice, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								ann = mapper.readValue(obj.getString("data"),
										new TypeReference<Annouce>() {
										});
								handler.sendEmptyMessage(DETAIL_SUCCESS);
							} else {
								handler.sendEmptyMessage(DETAIL_FAIL);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(DETAIL_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(DETAIL_FAIL);
					}

				});
	}

	public final int DETAIL_SUCCESS = 0x2210;
	public final int DETAIL_FAIL = DETAIL_SUCCESS + 1;
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			dialog.dismiss();
			switch (msg.what) {
			case DETAIL_SUCCESS:
				if (ann != null) {
					title_tv.setText(ann.getNewtitle());
					time_tv.setText(ann.getAddtime() + "      "
							+ ann.getAuthor());
					content_tv.setText(Html.fromHtml(ann.getNewcontent(),
							new MyImageGetter(AnnounceDetailActivity.this,
									content_tv), null));
				}
				break;
			case DETAIL_FAIL:
				finish();
				Toast.makeText(AnnounceDetailActivity.this, "获取失败", 500).show();
				break;
			}
		};
	};

	public class MyImageGetter implements ImageGetter {

		private Context context;
		private TextView tv;

		public MyImageGetter(Context context, TextView tv) {
			this.context = context;
			this.tv = tv;
		}

		@Override
		public Drawable getDrawable(String source) {
			// TODO Auto-generated method stub
			// 将source进行MD5加密并保存至本地
			if (!source.startsWith("http")) {
				source = "http://www.smartcity.sh" + source;
			}
			LogUtil.d("wxf", "source=" + source);
			String imageName = MD5.encode(source);
			String sdcardPath = Environment.getExternalStorageDirectory()
					.toString(); // 获取SDCARD的路径
			// 获取图片后缀名
			String[] ss = source.split("\\.");
			String ext = ss[ss.length - 1];

			// 最终图片保持的地址
			String savePath = sdcardPath + "/" + context.getPackageName() + "/"
					+ imageName + "." + ext;

			File file = new File(savePath);
			if (file.exists()) {
				// 如果文件已经存在，直接返回
				Drawable drawable = Drawable.createFromPath(savePath);
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight());
				return drawable;
			}

			// 不存在文件时返回默认图片，并异步加载网络图片
			Resources res = context.getResources();
			URLDrawable drawable = new URLDrawable(
					res.getDrawable(R.drawable.bucket_no_picture));
			new ImageAsync(drawable).execute(savePath, source);
			return drawable;

		}

		private class ImageAsync extends AsyncTask<String, Integer, Drawable> {

			private URLDrawable drawable;

			public ImageAsync(URLDrawable drawable) {
				this.drawable = drawable;
			}

			@Override
			protected Drawable doInBackground(String... params) {

				InputStream in = null;// TODO Auto-generated method stub
				try {
					String savePath = params[0];
					String url = params[1];

					// 获取网络图片
					HttpGet http = new HttpGet(url);
					HttpClient client = new DefaultHttpClient();
					HttpResponse response = (HttpResponse) client.execute(http);
					BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
							response.getEntity());
					in = bufferedHttpEntity.getContent();

					if (in == null)
						return drawable;

					File file = new File(savePath);
					String basePath = file.getParent();
					File basePathFile = new File(basePath);
					if (!basePathFile.exists()) {
						basePathFile.mkdirs();
					}
					file.createNewFile();
					FileOutputStream fileout = new FileOutputStream(file);
					byte[] buffer = new byte[4 * 1024];
					while (in.read(buffer) != -1) {
						fileout.write(buffer);
					}
					fileout.flush();
					Drawable mDrawable = Drawable.createFromPath(savePath);
					return mDrawable;

				} catch (Exception e) {
					try {
						if (in != null)
							in.close();
					} catch (Exception e2) {
						// TODO: handle exception
					}
				}
				return drawable;
			}

			@Override
			protected void onPostExecute(Drawable result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (result != null) {
					drawable.setDrawable(result);
					tv.setText(tv.getText()); // 通过这里的重新设置 TextView 的文字来更新UI
				}
			}

		}

		public class URLDrawable extends BitmapDrawable {

			private Drawable drawable = null;

			public URLDrawable(Drawable defaultDraw) {
				if (defaultDraw == null)
					return;
				setDrawable(defaultDraw);
			}

			private void setDrawable(Drawable nDrawable) {
				if (nDrawable == null)
					return;
				drawable = nDrawable;
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight());
				setBounds(0, 0, drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight());
			}

			@Override
			public void draw(Canvas canvas) {
				try {
					if (drawable != null) {
						drawable.draw(canvas);
					}
				} catch (StackOverflowError e) {

				}
			}

		}
	}

}
